﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace ReguLiteCM
{
	/// <summary>
	/// 
	/// </summary>
	internal class DotNetRegexStrategy : IRegexStrategy
	{
		readonly private string _expression;
		readonly private string _input;

		/// <summary>
		/// 
		/// </summary>
		public bool Global { get;set; }

		/// <summary>
		/// 
		/// </summary>
		public bool IgnoreCase { get;set; }

		public bool MultiLine { get;set; }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="expression"></param>
		/// <param name="input"></param>
		public DotNetRegexStrategy(string expression, string input)
		{
			_expression = expression;
			_input = input;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public IEnumerable<string> FindMatches()
		{
			Regex regex = new Regex(_expression, Options);

			if (regex.IsMatch(_input))
			{
				if (Global)
				{
					return regex.Matches(_input).Cast<Match>().Select(m => m.Value).ToList();
				}
				
				IList<string> result = new List<string>(1);
				result.Add(regex.Match(_input).Value);

				return result;
			}

			return null;
		}

		/// <summary>
		/// 
		/// </summary>
		protected RegexOptions Options
		{
			get
			{
				RegexOptions options = RegexOptions.None;
				if (IgnoreCase)
				{
					options = (options | RegexOptions.IgnoreCase);
				}
				if (MultiLine)
				{
					options = (options | RegexOptions.Multiline);
				}
				return options;
			}
		}
	}
}